//
//  DoingPaperMainController.m
//  DoingPaper
//
//  Created by zhuxuhong on 16/7/25.
//  Copyright © 2016年 zhuxuhong. All rights reserved.
//

#import "DoingPaperMainController.h"
#import "PaperResultController.h"


#pragma mark DoingPaperMainController
@implementation DoingPaperMainController

-(instancetype)initWithParams:(NSDictionary *)dict submitPaperCompletion:(SubmitPaperCompletion)completion{
    /*dict                                    = @{
     @"parent_id": @"568D0276-799B-96E5-7F78-7B41C668DBFE",
     @"projeck_host": @"http://172.19.42.53:8509",
     @"quizid": @"9303620D-0287-243B-28A1-300FB890A541",
     @"role": @"student",
     @"simulate_exam_result_id": @"112002",
     @"status":  @"0",
     @"user_id": @"EFDD8B11-3038-137A-0217-C8BCF9D1D384",
     @"uuid": @"0BD17A83-87C2-0308-3B50-201075BFBDB5"
     };*/
    
    DoingPaperController *vc = [[DoingPaperController alloc]initWithParams:dict submitPaperCompletion:completion];
    return [super initWithRootViewController: vc];
}

-(void)viewDidLoad{
    [super viewDidLoad];
    self.navigationBar.translucent = false;
}

-(BOOL)shouldAutorotate{
    return true; // 触发自动旋转
}

//-(UIInterfaceOrientationMask)supportedInterfaceOrientations{
//    return UIInterfaceOrientationMaskPortrait;
//}

@end



#pragma mark DoingPaperController

@interface DoingPaperController ()<UIScrollViewDelegate,UIAlertViewDelegate>

@property(nonatomic,strong)UIScrollView* scrollView;
@property(nonatomic,strong)UIView *headView;
// 答题用时
@property(nonatomic,assign)NSInteger totalUsedTime;
@property(nonatomic,assign)NSInteger currentPage;
@property(nonatomic,copy)PaperItemCellTableView *currentQuestionView; //当前正在展示的view
@property(nonatomic,copy)PaperQuestion *currentQuestion; //当前正在展示的qst
@property(nonatomic,strong)ImageTitleButton *collectBtn; //收藏按钮

@end

#pragma mark DoingPaperController
@implementation DoingPaperController
{
    CGFloat screenW;
    CGFloat screenH;
    CGFloat headViewH;
    UILabel *indexLabel;
    UILabel *timeLabel;
    NSTimer *timer;
    UIAlertView *submitPaperAlert;
    PaperDataManager *dataManager;
    SubmitPaperCompletion completionBlock;
}

-(instancetype)initWithParams:(NSDictionary *)dict
        submitPaperCompletion:(SubmitPaperCompletion)completion{
    completionBlock = completion;
    
    return [self initWithParams:dict];
}

-(instancetype)initWithParams: (NSDictionary*)dict{
    NSLog(@"doing paper param: %@",dict);
    
    if (self = [super init]) {
        dataManager = [PaperDataManager sharedManager] ;
        _paper = [PaperModel new];
        _param = [PaperParam paramWithDictionary:dict];
        
        screenW = [UIScreen mainScreen].bounds.size.width;
        screenH = [UIScreen mainScreen].bounds.size.height;

        headViewH = 44;
    }
    return self;
}

-(BOOL)iOS7{
    float version = [[UIDevice currentDevice].systemVersion floatValue];
    return version >= 7.0 && version < 8.0;
}

#pragma mark - lifecycle
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];

    if (!_paper.paperId) {
        [self loadPaper];
    }
    
    [self startNetworkMonitoring];
}

// 网络监测
-(void)startNetworkMonitoring{
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));
    }];
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
}

-(void)setupUI{
    self.view.backgroundColor = [UIColor whiteColor];

    // nav
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(dismiss)];

    self.navigationItem.rightBarButtonItem  = [[UIBarButtonItem alloc]initWithTitle:@"选项卡" style:UIBarButtonItemStylePlain target:self action:@selector(toPaperCardPage)];

    [self.view addSubview: self.headView];
    [self.view addSubview: self.scrollView];

    [self setupToolbarNeedShowAnswerScanItem:true enabledItem:false];
}

-(void)dismiss{
    // 记得关掉计时器
    if (timer) {
        [self stopTimer];
    }
    
    if (_isCollectQuestionsScanning) {
        [self.navigationController popViewControllerAnimated:true];
    }
    else{
        [self dismissViewControllerAnimated:true completion:^{
            completionBlock ? completionBlock() : nil;
        }];
    }
}

-(BOOL)canBecomeFirstResponder{
    return true;
}

-(void)setupToolbarNeedShowAnswerScanItem: (BOOL)show
                               enabledItem: (BOOL)enabled{
    UIToolbar *toolBar = self.navigationController.toolbar;
    toolBar.translucent = false;
    UIBarButtonItem *flexItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
//    [toolBar setBackgroundImage:[UIImage imageNamed:@"top_bar_ios7_bg"] forToolbarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
    toolBar.barTintColor = [UIColor blackColor];

    UIBarButtonItem *answerScanItem = [self toolbarItemWithTitle:@"查看答案" iconName:nil action:@selector(scanQuestionAnswer:) isCollectBtn: false enabled: enabled];
    if (!_param.submited){
        self.toolbarItems = @[
            flexItem,
            [self toolbarItemWithTitle:@"交卷" iconName:@"icon_toolbar_submit" action:@selector(submitPaper) isCollectBtn: false enabled:enabled],
            flexItem
        ];
    }
    else{
        if (show) {
            self.toolbarItems = @[
              flexItem,
              [self toolbarItemWithTitle:@"收藏" iconName:@"icon_toolbar_collect" action:@selector(collectQuestion:) isCollectBtn: true enabled: enabled],
              answerScanItem,
              flexItem
              ];
        }
        else
        {
            {self.toolbarItems = @[
               flexItem,
               [self toolbarItemWithTitle:@"收藏" iconName:@"icon_toolbar_collect" action:@selector(collectQuestion:) isCollectBtn: true enabled: enabled],                                 flexItem
               ];
            }
        }
        
    }
}

-(UIBarButtonItem*)toolbarItemWithTitle: (NSString*)title iconName: (NSString*)icon action: (SEL)action isCollectBtn: (BOOL)collect enabled: (BOOL)enabled{
    CGFloat w = title.length * 32 + 10;
    ImageTitleButton *btn = [[ImageTitleButton alloc]initWithFrame:CGRectMake(0, 0, w, 44) imageName:icon title:title];
    btn.titleLabel.font = [UIFont systemFontOfSize:16];
    [btn addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView: btn];
    item.enabled = enabled;
    if (collect) {
        _collectBtn = btn;
    }
    return item;
}

-(void)setPaper:(PaperModel *)paper{
    if (paper) {
        self.navigationItem.title = paper.title;
        _paper = paper;
        _paper.paperId = _param.paperId;
        _param.paperName = _paper.title;
        _paper.submited = _param.submited;
        
        // 更新数据
        if (_isCollectQuestionsScanning) {
            [self updateData];
        }
        [self reloadData];
        
        if (!_param.submited) {
            [self startTimer];
        }
        
        // 选项通知
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(scrollToNextQuestion) name:@"DidSelectOptionNoti" object:nil];
        
        // toolbar items 可用
        for (UIBarButtonItem *item in self.navigationController.toolbar.items) {
            item.enabled = true;
        }
    }
}

// setters
-(NSString *)paperImagesBaseUrl{
    return [dataManager paperImagesPathWithId: _paper.paperId];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.navigationController.toolbarHidden = true;
}


#pragma mark 懒加载
-(UIView *)headView{
    if (!_headView) {
        UIView *view = [UIView new];
        view.backgroundColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.5];

        // 左边显示当前第几题 1/3
        indexLabel = [UILabel new];
        indexLabel.textAlignment = NSTextAlignmentCenter;
        indexLabel.text = @"0/0";

        // 右边计时label
        timeLabel = [UILabel new];
        timeLabel.textAlignment = NSTextAlignmentRight;

        [view addSubview:indexLabel];
        [view addSubview:timeLabel];

        _headView = view;
        
        [self updateHeadViewFrame];
    }

    return _headView;
}

-(UIScrollView *)scrollView{
    if (!_scrollView) {
        UIScrollView *sv = [UIScrollView new];
        sv.pagingEnabled = true;
        sv.delegate      = self;
        _scrollView      = sv;
    }
    return _scrollView;
}

-(PaperQuestion *)currentQuestion{
    _currentQuestion = self.currentQuestionView.question;
    return _currentQuestion;
}

-(PaperItemCellTableView *)currentQuestionView{
    _currentQuestionView = (PaperItemCellTableView*)_scrollView.subviews[_currentPage];
    return _currentQuestionView;
}

#pragma mark - 计算frame
-(void)updateScrollViewFrame{
    CGFloat h = self.navigationController.isToolbarHidden ? 0 : 64;
    CGRect frame = CGRectMake(0, headViewH, screenW, screenH-headViewH-20-h);
    _scrollView.frame = frame;
    
    CGFloat x = 0;
    for (int i=0; i<_scrollView.subviews.count; i++) {
        UIView *tb = _scrollView.subviews[i];
        if ([tb isMemberOfClass:[PaperItemCellTableView class]]) {
            tb = (PaperItemCellTableView*)tb;
            CGRect frame = _scrollView.bounds;
            frame.origin.x = x;
            tb.frame = frame;
            x += frame.size.width;
        }
    }
    NSInteger total = _paper.totalQuestionsCount;
    if (_isCollectQuestionsScanning) {
        total = _collectQuestions.count;
    }
    _scrollView.contentSize = CGSizeMake(frame.size.width * total, frame.size.height);
}

-(void)updateHeadViewFrame{
    CGRect frame1 = CGRectMake(0, 0, screenW, headViewH);
    CGRect frame2 = CGRectMake(screenW/2-200, 0, 400, headViewH);
    CGRect frame3 = CGRectMake(screenW-300-20, 0, 300, headViewH);
    
    _headView.frame = frame1;
    indexLabel.frame = frame2;
    timeLabel.frame = frame3;
}

// 更新数据，筛选试卷中已经收藏的题
-(void)updateData{
    for (PaperItem *item in _paper.items)
    {
        for (PaperQuestion *q in item.questions)
        {
            q.submited = true;
            for (PaperCollectQuestion *qst in _collectQuestions)
            {
                if (qst.topicId == [q.qstId integerValue]) {
                    q.collected = true;
                }
            }
        }
    }
}

// 刷新数据
-(void)reloadData{
    for (int i = 0; i<_paper.items.count; i++) {
        PaperItem *item = _paper.items[i];
        for (int j = 0; j<item.questions.count; j++)
        {
            PaperQuestion *q = item.questions[j];
            if (!_param.submited || (_isCollectQuestionsScanning && q.collected) || (!_isCollectQuestionsScanning && _param.submited))
            {
                q.paperId = _paper.paperId;
                q.submited = _param.submited;
                q.typeName = item.typeName;
                q.questionNum = j+1;
                q.contentViewHeight = 0;
                q.analysisFooterHeight = 0;
                
                // 重置选项数据
                for (PaperQuestionOption *op in q.options) {
                    op.contentViewHeight = 0;
                }
                
                PaperItemCellTableView *tb = [[PaperItemCellTableView alloc]initWithFrame:self.view.bounds question:q];
                tb.contentInset = UIEdgeInsetsMake(0, 0, 64, 0);
                tb.isScanningAnswer = q.submited;
                [_scrollView addSubview:tb];
            }
        }
    }
    [self updateScrollViewFrame];
    [self scrollToCurrentPage];
}

#pragma mark - 答完题浏览
-(void)scanPaper{
    if (![dataManager checkNetworkConnection]) {
        return;
    }
    __weak typeof(self) weakSelf = self;
    [dataManager scanPaperWithSubmitedPaper:_paper Param:_param succeed:^{
        [weakSelf reloadData];
    } finished:^{

    } failed:^(NSError *error) {
        [self HUDShowText:error.domain successType:false];
        NSLog(@"error: %@",error.domain);
    }];
}

#pragma mark - 答题卡
-(void)toPaperCardPage{
    [self.navigationItem setValue:@"返回" forKeyPath:@"_backButtonTitle"];
    self.navigationController.toolbarHidden = true;
    __weak typeof(self) weakSelf = self;
    PaperCardController *vc = [[PaperCardController alloc]initWithPaperModel: _paper clickedCell:^(NSInteger index) {
        weakSelf.currentPage = index;
        [weakSelf scrollToCurrentPage];
    }];
    vc.isCollectQuestionsScanning = _isCollectQuestionsScanning;
    [self.navigationController pushViewController:vc animated:true];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.toolbarHidden = false;
}

#pragma mark - 加载试题
-(void)loadPaper{
    MBProgressHUD *hud = [self showLoadingHUDWithMessage:@"正在加载试卷..."];
    PaperModel *paper = [dataManager loadPaperWithPaperId:_param.paperId];
    if (paper) {
        self.paper = paper;
        [hud hideAnimated:true];
    }
    else{
        [self initPaperWithHUDShowing: hud];
    }
}

#pragma mark - 获取网络试题
-(void)initPaperWithHUDShowing: (MBProgressHUD*)hud{
    if (![dataManager checkNetworkConnection]) {
        return;
    }
    __weak typeof(self) weakSelf = self;
    [dataManager getPaperWithParam:_param succeed:^(PaperModel *paper) {
        weakSelf.paper = paper;
        [hud hideAnimated:true];
    } finished:^{
        NSLog(@"finished");
    } failed:^(NSError *error) {
        [hud hideAnimated:true];
        [weakSelf HUDShowText:error.domain successType:false];
        NSLog(@"error: %@",error.domain);
    }];
}

-(void)HUDShowText: (NSString*)text successType: (BOOL)success{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSTimeInterval time = (success) ? 1 : 2;
//    hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
    hud.mode = MBProgressHUDModeText;
    hud.label.text = text;
    [hud hideAnimated:true afterDelay:time];
    hud.contentColor = [UIColor blackColor];
}


// 查看答案
-(void)scanQuestionAnswer: (UIButton*)sender{
//    NSLog(@"current question: %@",_currentQuestion.qstId);
    self.currentQuestionView.isScanningAnswer = !_currentQuestionView.isScanningAnswer;
}

#pragma mark - 收藏/取消收藏
-(void)collectQuestion: (ImageTitleButton*)sender{
    __weak typeof(self) weakSelf = self;
    if (!self.currentQuestion.collected) {
        [[PaperDataManager sharedManager] collectPaperNewWithQuestion:self.currentQuestion paperParam:_param succeed:^{
            weakSelf.currentQuestion.collected = true;
            [weakSelf HUDShowText:@"收藏成功" successType:true];
            [weakSelf updateUIOfCollectBtnIsCollected:true];
            
        } failed:^(NSError *error) {
            [weakSelf HUDShowText:error.domain successType:false];
        }];
    }
    else{
        [[PaperDataManager sharedManager] cancelCollectPaperNewWithQuestion:self.currentQuestion paperParam:_param succeed:^{
            weakSelf.currentQuestion.collected = false;
            [weakSelf HUDShowText:@"取消收藏成功" successType:true];
            [weakSelf updateUIOfCollectBtnIsCollected:false];
        } failed:^(NSError *error) {
            [weakSelf HUDShowText:error.domain successType:false];
        }];
    }
}

// 更新collect btn UI
-(void)updateUIOfCollectBtnIsCollected: (BOOL)isCollected{
    NSString *iconName = isCollected ? @"icon_toolbar_collected" : @"icon_toolbar_collect";
    NSString *title = isCollected ? @"取消收藏" : @"收藏";
    dispatch_async(dispatch_get_main_queue(), ^{
        [_collectBtn setTitle:title iconImage:iconName];
        
        // frame
        CGRect frame = _collectBtn.frame;
        frame.size.width = title.length * 32 + 10;
        _collectBtn.frame = frame;
    });
}


/**
 *  交卷
 */
-(void)submitPaper{
    if (![dataManager checkNetworkConnection]) {
        return;
    }
    
    // 统计没有做完的题
    NSInteger unfinished = [self unfinishedQuestionCountForPaper: _paper];

    if (unfinished > 0) {
        // 提示
        NSString *message = [NSString stringWithFormat:@"你还有 %ld 道题未完成",unfinished];
        submitPaperAlert = [self showAlertViewWithTitle:@"确定要交卷?" message:message cancelButtonTitle:@"继续做完" okButtonTitle:@"任性交卷"];
    }
    else{
        [self confirmSubmitPaper];
    }
}

// get unfinished question count
-(NSInteger)unfinishedQuestionCountForPaper: (PaperModel*)paper{
    NSInteger unfinished = 0;
    for (PaperItem *item in paper.items) {
        for (PaperQuestion *q in item.questions) {
            unfinished += !q.userAnswer ? 1 : 0;
        }
    }
    return unfinished;
}

#pragma mark - 确认交卷
-(void)confirmSubmitPaper{
    // 停止计时
    _paper.usedTime = [NSString stringWithFormat:@"%ld",_totalUsedTime];
    [self stopTimer];

    __weak typeof(self) weakSelf = self;
    MBProgressHUD *hud = [self showLoadingHUDWithMessage:@"正在交卷..."];
    [dataManager submitPaperNewWithPaper:_paper PaperParam:_param succeed:^{
        [hud hideAnimated:true];
        [weakSelf submitPaperSucceed];
    } failed:^(NSError *error) {
        [hud hideAnimated:true];
        [weakSelf HUDShowText:error.domain successType:false];
    }];
}

-(void)submitPaperSucceed{
    [self HUDShowText:@"交卷成功" successType:true];
    
    // 跳转到查看答案页面
    PaperResultController *rvc = [PaperResultController new];
//    rvc.modalPresentationStyle = UIModalPresentationFormSheet;
    rvc.paper = _paper;
    __weak typeof(self) weakSelf = self;
    rvc.scanAnswerBlock = ^(void){
        weakSelf.param.submited = true;
        // 滚动到第一题
        weakSelf.currentPage = 0;
        [weakSelf scrollToCurrentPage];
        for (PaperItem *item in _paper.items) {
            for (PaperQuestion *q in item.questions) {
                q.submited = true;
            }
        }
        // 刷新页面，交卷成功展示
        [weakSelf refreshMainUIForSucceedSubmitPaper];
    };
    [self presentViewController:rvc animated:true completion:nil];
}

-(void)refreshMainUIForSucceedSubmitPaper{
    for (UIView *subview in _scrollView.subviews) {
        if ([subview isMemberOfClass:[PaperItemCellTableView class]]) {
            PaperItemCellTableView *tb = (PaperItemCellTableView*)subview;
            tb.isScanningAnswer = true;
            [tb reloadData];
        }
    }
    
    [self setupToolbarNeedShowAnswerScanItem:false enabledItem:true];
}

-(MBProgressHUD*)showLoadingHUDWithMessage: (NSString*)text{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[self keyWindow] animated:true];
    hud.label.text = text;
    [hud showAnimated:true];
    return hud;
}

-(UIWindow*)keyWindow{
    return [UIApplication sharedApplication].keyWindow;
}

#pragma mark - showAlertView
-(UIAlertView*)showAlertViewWithTitle: (NSString*)title
                              message: (NSString*)message
           cancelButtonTitle: (NSString*)cancel
               okButtonTitle: (NSString*)ok{

    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:title message:message delegate:self cancelButtonTitle:cancel otherButtonTitles:ok, nil];
    [alert show];
    return alert;
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView == submitPaperAlert) {
        if (buttonIndex == 1) {
            [self confirmSubmitPaper];
        }
    }
}

-(void)setCurrentPage:(NSInteger)currentPage{
    NSInteger total = _paper.totalQuestionsCount;
    if (_isCollectQuestionsScanning) {
        total = _collectQuestions.count;
    }
    indexLabel.text = [NSString stringWithFormat:@"第%ld题 / 共%ld题",
                       currentPage+1, total];

    // cell结束编辑
    [self becomeFirstResponder];

    _currentPage = currentPage;
    
    // 更新收藏按钮样式
    if (_param.submited) {
        [self updateUIOfCollectBtnIsCollected:self.currentQuestion.collected];
    }
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    NSInteger page = scrollView.contentOffset.x / CGRectGetWidth(scrollView.bounds) + 0.5;
    self.currentPage = page;
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    if (_isCollectQuestionsScanning) {
        return;
    }
    if (_currentPage == 0) {
        [self HUDShowText:@"已经是第一题" successType:true];
    }
    else if (_currentPage+1 == _paper.totalQuestionsCount) {
        [self HUDShowText:@"已经是最后一题" successType:true];
    }
}

// scroll to next
-(void)scrollToNextQuestion{
    if (_currentPage+1 == _paper.totalQuestionsCount) {
        return;
    }

    self.currentPage += 1;
    CGFloat x = _currentPage * CGRectGetWidth(_scrollView.bounds);

    [UIView animateWithDuration:0.5 animations:^{
        _scrollView.contentOffset = CGPointMake(x, 0);
    }];
}

// scroll to page
-(void)scrollToCurrentPage{
    self.currentPage = _currentPage;
    _scrollView.contentOffset = CGPointMake(_currentPage * screenW, 0);
}

// 计时
-(void)startTimer{
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerForRefreshLabelText) userInfo:nil repeats:true];
    [timer fire];
    _paper.startTime = [self formattedTimeStringForPaperDoing];
}

-(void)stopTimer{
    [timer invalidate];
    timer = nil;
    _paper.finishTime = [self formattedTimeStringForPaperDoing];
}

// 做题时间
-(NSString*)formattedTimeStringForPaperDoing{
    NSDateFormatter *df = [NSDateFormatter new];
    df.dateFormat = @"yyyy-MM-dd HH:mm:ss.aaa";
    return [df stringFromDate:[NSDate date]];
}

-(void)timerForRefreshLabelText{
    _totalUsedTime += 1;
    timeLabel.text = [self textForFormattedTimeString: _totalUsedTime];
}

-(NSString*)textForFormattedTimeString: (NSInteger)seconds{
    NSInteger h = seconds / 3600;
    NSInteger m = seconds % 3600 / 60;
    NSInteger s = seconds % 60;

    return [NSString stringWithFormat:@"%02ld:%02ld:%02ld",h,m,s];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 横竖屏
-(void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{
    NSLog(@"toOrientation: %ld",toInterfaceOrientation);
    
    if (toInterfaceOrientation == UIInterfaceOrientationPortrait || toInterfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) {
        screenW = MIN(CGRectGetWidth([UIScreen mainScreen].bounds),
                      CGRectGetHeight([UIScreen mainScreen].bounds));
        screenH = MAX(CGRectGetWidth([UIScreen mainScreen].bounds),
                      CGRectGetHeight([UIScreen mainScreen].bounds));
    }
    else if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft || toInterfaceOrientation == UIInterfaceOrientationLandscapeRight){
        screenW = MAX(CGRectGetWidth([UIScreen mainScreen].bounds),
                      CGRectGetHeight([UIScreen mainScreen].bounds));
        screenH = MIN(CGRectGetWidth([UIScreen mainScreen].bounds),
                      CGRectGetHeight([UIScreen mainScreen].bounds));
    }
    
//    NSLog(@"w: %lf h: %lf",screenW,screenH);
    
    // 重置frame
    [self updateHeadViewFrame];
    [_scrollView removeFromSuperview];
    _scrollView = nil;
    [self.view addSubview:self.scrollView];
    [self reloadData];
}


@end
